package com.bbx.taxi.client.DB.MyOrder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bbx.api.sdk.model.passanger.Token;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.End;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.Location;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.Locations;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.MyOrderList;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.Start;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.DB.Util.DBHelper;
import com.bbx.taxi.client.DB.Util.DBcolumns;

import android.R.integer;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;

/**
 * 我的订单
 * 
 */
public class MyOrderDB implements DBcolumns {
	private DBHelper helper;

	public MyOrderDB() {
		MyApplication myApplication=MyApplication.getInstance();
		helper = DBHelper.getInstance(myApplication.getApplicationContext(),myApplication.getUid());
	}

	/**
	 * 打开只读的数据库
	 */
	public SQLiteDatabase onOpenRead() {
		if(helper==null){
			helper = DBHelper.getInstance(MyApplication.getInstance().getApplicationContext(), null);
		}
		SQLiteDatabase SQLdb ;
		try{SQLdb= helper.getReadableDatabase();}catch(Exception e){
			helper = DBHelper.getInstance(MyApplication.getInstance().getApplicationContext(), null);
			SQLdb= helper.getReadableDatabase();
		}
		return SQLdb;
	}

	/**
	 * 打开只写的数据库
	 */
	public SQLiteDatabase onOpenWrite() {
		if(helper==null){
			helper = DBHelper.getInstance(MyApplication.getInstance().getApplicationContext(), null);
		}
		SQLiteDatabase SQLdb ;
		try{SQLdb= helper.getReadableDatabase();}catch(Exception e){
			helper = DBHelper.getInstance(MyApplication.getInstance().getApplicationContext(), null);
			SQLdb= helper.getReadableDatabase();
		}
		return SQLdb;
	}

	/**
	 * 查询全部
	 */
	public Cursor onQuery() {
		SQLiteDatabase SQLdb = onOpenRead();
		Cursor cursor = SQLdb.query(TABLE_ORDER, null, null, null, null,
				null, ORDER_ID + " desc ");
		return cursor;

	}

	/**
	 * 根据订单id查询
	 */
	public Cursor onQuery(String order_id) {
		SQLiteDatabase SQLdb = onOpenRead();
		Cursor cursor = SQLdb.query(TABLE_ORDER, null, MYORDER_ID
				+ "='" + order_id + "'", null, null, null, ORDER_ID
				+ " desc ");
		return cursor;

	}

	/**
	 * 用于分页查询，指定数量，指定id,按降序查询，不能大于id
	 */
	public Cursor onQuery(int id, int count) {
		SQLiteDatabase SQLdb = onOpenRead();
		Cursor cursor = null;
		if (id == -1) {
			cursor = SQLdb.query(TABLE_ORDER, null, null, null, null, null,
					ORDER_ID + " desc  LIMIT 0," + count);
		} else {
			cursor = SQLdb.query(TABLE_ORDER, null, MYORDER_ID + "<" + id,
					null, null, null, ORDER_ID + " desc  LIMIT " + count);
		}

		return cursor;

	}

	/**
	 * 删除整个表
	 */
	public void onDelete() {
		SQLiteDatabase SQLdb = onOpenWrite();
		SQLdb.delete(TABLE_ORDER, null, null);
		SQLdb.close();
	}

	/**
	 * 删除订单Id
	 */
	public void onDelete(Context context, String order_id) {
		SQLiteDatabase SQLdb = onOpenWrite();
		String[] whereArgs = { String.valueOf(order_id) };
		int i = SQLdb.delete(TABLE_ORDER, MYORDER_ID + "='" + order_id
				+ "'", null);
		SQLdb.close();
	}
	/**
	 * 更新全部数据
	 */
	public void onUpdate(MyOrderList mMyOrderList){
		onUpdate(mMyOrderList.getOrder_id(),mMyOrderList);
	}
	/**
	 * 更新一条数据,根据order_id修改司机状态
	 */
	public void onUpdate(String myorder_id, int order_status, String driver_id,
			String driver_name, String car_NO, String driver_phone,
			double driver_star) {
		MyOrderList mMyOrderList=onReadDB(myorder_id);
		mMyOrderList.setOrder_status(order_status);
		mMyOrderList.setDriver_id(driver_id);
		mMyOrderList.setDriver_name(driver_name);
		mMyOrderList.setCar_NO(car_NO);
		mMyOrderList.setDriver_phone(driver_phone);
		mMyOrderList.setDriver_star(driver_star);
		onUpdate(myorder_id,mMyOrderList);
	}

	/**
	 * 更新一条数据,根据order_id修改订单状态
	 */
	public void onUpdate(String myorder_id, int myorder_order_status) {
		MyOrderList mMyOrderList=onReadDB(myorder_id);
		mMyOrderList.setOrder_status(myorder_order_status);
		onUpdate(myorder_id,mMyOrderList);
	}

	/**
	 * 更新一条数据,根据order_id修改评价状态
	 */
	public void onUpdateValuate(String myorder_id, int valuate_status) {
		MyOrderList mMyOrderList=onReadDB(myorder_id);
		mMyOrderList.setValuate_status(valuate_status+"");
		onUpdate(myorder_id,mMyOrderList);
	}
	public void onUpdate(String order_id,MyOrderList mMyOrderList){
		String json = new JsonBuild().setModel(mMyOrderList).getJsonString(false);
		SQLiteDatabase SQLdb = onOpenWrite();
		ContentValues cv = new ContentValues();
		cv.put(MYORDER_STATUS, mMyOrderList.getOrder_status());
		cv.put(MYORDER_JSON, json);
		SQLdb.update(TABLE_ORDER, cv, MYORDER_ID + "='" + order_id
				+ "'", null);
		SQLdb.close();
	}
	/**
	 * 插入一条数据
	 */
	public void onWrite(String order_id,int status,String json) {
		SQLiteDatabase SQLdb = onOpenWrite();
		ContentValues values = new ContentValues();
		values.put(MYORDER_ID, order_id);
		values.put(MYORDER_STATUS, status);
		values.put(MYORDER_JSON, json);
		SQLdb.insert(TABLE_ORDER, ORDER_ID, values);
		SQLdb.close();
	}

	/**
	 * 关闭数据库
	 */
	public void onColse() {
		SQLiteDatabase SQLdb = onOpenWrite();
		SQLdb.close();
	}

	/**
	 * 写入全部订单数据（单笔）
	 */
	public void onWriteDB(MyOrderList mMyOrderList) {
		if(mMyOrderList!=null){
			String order_id=mMyOrderList.getOrder_id();
			int status=mMyOrderList.getOrder_status();
			String json = new JsonBuild().setModel(mMyOrderList).getJsonString(false);
			onWrite(order_id,status,json);
		}
	}

	/**
	 * 写入全部订单数据（多笔）必须是所有的数据
	 */
	public void onWriteDB(final ArrayList<MyOrderList> list,final boolean isDelete,final Handler mHandler) {
		new AsyncTask<Void, Void, Void>(){

			@Override
			protected Void doInBackground(Void... params) {
				if(isDelete){
				   onDelete();
				}
				// 逆序插入，因为list最新数据在在第一个，数据库的ID要最大，所以要逆序
				for (int i = list.size() - 1; i >= 0; i--) {
					MyOrderList mMyOrderList=list.get(i);
					if(mMyOrderList!=null){
						String order_id=mMyOrderList.getOrder_id();
						int status=mMyOrderList.getOrder_status();
						String json = new JsonBuild().setModel(mMyOrderList).getJsonString(false);
						onWrite(order_id,status,json);
					}
				}
				if(mHandler!=null)
					mHandler.sendEmptyMessage(BaseBBXActivity.MSG_ORDER_WRITE);
				return null;
			}}.execute();
	}

	/**
	 * 根据订单ID查询并返回MyOrderList数据
	 */
	public MyOrderList onReadDB(String order_id) {
		if(order_id==null)return null;
		MyOrderList mMyOrderList = new MyOrderList();
		Cursor c = onQuery(order_id);
		c.moveToFirst();
		if (c.getCount() > 0) {
			do {
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < c.getColumnCount(); i++) {
					map.put(c.getColumnName(i), c.getString(i));
				}
				 mMyOrderList = (MyOrderList) new JsonBuild().getData(MyOrderList.class,
						 map.get(DBcolumns.MYORDER_JSON));
			} while (c.moveToNext());
		}
		c.close();
		onColse();
		return mMyOrderList;
	}

	/**
	 * 读取全部订单数据库数据,根据类型
	 */
	public ArrayList<MyOrderList> onReadDB(int num) {
		ArrayList<MyOrderList> list_all = new ArrayList<MyOrderList>();
		Cursor c = onQuery(-1, num);
		c.moveToFirst();
		if (c.getCount() > 0) {
			do {
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < c.getColumnCount(); i++) {
					map.put(c.getColumnName(i), c.getString(i));
				}
				try{
				 MyOrderList mMyOrderList = (MyOrderList) new JsonBuild().getData(MyOrderList.class,
						 map.get(DBcolumns.MYORDER_JSON));
				list_all.add(mMyOrderList);
				}catch(Exception e){}
			} while (c.moveToNext());
		}
		c.close();
		onColse();
		return list_all;
	}
}
